import React, { useState, useEffect } from "react";

import style from "./index.module.scss";
import { Button } from "antd";
import { Editor } from "../Editor";
import { EditBlock } from "./editor-block";
import { CommentApi } from "@/api/comment";
import { CommentItem } from "./CommentItem";

interface IProps {
  isInHostPage: boolean;
  hostId: string;
  page?: number;
  pageSize?: number;
}
export const Comment: React.FC<IProps> = ({
  hostId,
  isInHostPage,
  page: defaultPage = 1,
  pageSize: defaultPageSize = 6,
}) => {
  const [comments, setComments] = useState<IComment[]>([]);
  const [page, setPage] = useState(defaultPage);
  const [pageSize, setpageSize] = useState(defaultPageSize);
  const [hasmore, setHasmore] = useState(true);
  useEffect(() => {
    CommentApi.getArticleComments(hostId, { page, pageSize }).then((res) => {
      const newComments = [...comments, ...res[0]];
      setComments(newComments);
      setHasmore(res[1] > newComments.length);
    });
  }, [page]);
  useEffect(() => {
    CommentApi.getArticleComments(hostId, { page, pageSize }).then((res) => {
      const newComments = res[0];
      setComments(newComments);
      setHasmore(res[1] > newComments.length);
    });
  }, [hostId]);
  return (
    <div className={style.wrapper}>
      <h2 className={style.title}>评论</h2>
      <div className={style.main}>
        {/* 页面第一级评论面板 */}
        <EditBlock
          hostId={hostId}
          isHostInPage={isInHostPage}
          parentComment={null}
          replyComment={null}
          onReply={() => {}}
        />
        {/* 评论列表 */}
        <div className={style.list}>
          {comments.map((comment, i) => (
            <CommentItem
              key={comment.id}
              comment={comment}
              subComment={comment?.children}
              isInHostPage={isInHostPage}
              hostId={hostId}
              parentComment={null}
              isChildren={false}
            />
          ))}
        </div>
        {/* 加载更多 */}
        {hasmore && (
          <div className={style.loadmore}>
            <a onClick={() => setPage(page + 1)}>加载更多</a>
          </div>
        )}
      </div>
    </div>
  );
};
